package com.practice.volidate示例;

/**
 * @program: tenghw-practice-demo
 * @author: tenghw
 * @create: 2024-01-19 01:01
 * @Version 1.0
 * @description:
 **/
public class VolatileExample {
    private volatile int counter = 0;
    public void increment() {
        counter++;
    }
    public int getCounter() {
        return this.counter;
    }
    public static void main(String[] args) throws InterruptedException {
        VolatileExample example = new VolatileExample();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment();
                if(i==9999){
                    System.out.println(example.counter);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                if (example.getCounter() >= 10000) {
                    System.out.println("Counter reached 10000 from t1-thread...");
                    break;
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("main最后执行");
    }

}